<template>
  <div class="chat">
    <el-drawer
      title="实时讨论"
      :visible.sync="drawer"
      size="500"
      direction="rtl"
    >
      <template slot="title">
        <h2 class="chat-title">实时讨论</h2>
      </template>
      <div class="chat-wrap">
        <template v-for="(item, index) in messageList">
          <div
            class="message-box"
            :key="index"
            :ref="'wrap' + index"
            v-if="item.userId == userinfo.userId"
          >
            <div class="my message">
              <el-avatar
                class="avatar"
                shape="square"
                :size="50"
                :src="item.avatar"
              ></el-avatar>
              <div class="content">
                <div class="nickname">
                  <span>{{ item.sendTime }}</span></div
                >
                <div class="bubble">
                  <div class="bubble_cont" v-html="item.msg"> </div>
                </div>
              </div>
            </div>
          </div>
          <div
            class="message-box"
            :key="index"
            :ref="'wrap' + index"
            v-if="item.userId != userinfo.userId"
          >
            <div class="other message">
              <el-avatar
                class="avatar"
                shape="square"
                :size="50"
                :src="item.avatar"
              ></el-avatar>
              <div class="content">
                <div class="nickname"
                  >{{ item.from }} <span>{{ item.sendTime }}</span></div
                >
                <div class="bubble">
                  <div class="bubble_cont" v-html="item.msg"> </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
      <div class="chat-form">
        <div class="emoji-wrap">
          <Emoji @emit="handleEmoji" />
        </div>
        <div class="toolbar">
          <ul>
            <li class="face" @click="handleShowEmoji()"></li>
          </ul>
        </div>
        <div class="chat-cont">
          <div class="text" id="myInput" contenteditable></div>
        </div>
        <div class="btn-wrap">
          <span class="desc">按下Ctrl发送</span>
          <el-button
            type="success"
            size="mini"
            @click.native="handleSubmit()"
            v-preventReClick
            >发 送</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getSession } from '@/utils/session'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import moment from 'moment'
let ROOM_URL = cfg.ROOM_URL
let headers = { Authorization: getSession('authorization') }
export default {
  components: {
    Emoji: () => import('@/components/emoji'),
  },
  data() {
    return {
      messageList: [],
      drawer: false,
      tableData: [],
      room: undefined,
      userList: [],
      userinfo: {
        username: undefined,
        avatar: undefined,
        room: undefined,
      },
    }
  },
  props: ['roomId'],
  mounted() {
    this.init()
    this.$bus.$on('openChatRoom', () => {
      this.drawer = true
    })
    window.addEventListener('keydown', this.keyDown)
  },
  beforeDestroy() {
    this.$bus.$off('openChatRoom')
    window.removeEventListener('keydown', this.keyDown, false)
  },
  methods: {
    init() {
      ROOM_URL = ROOM_URL + this.roomId
      let { userId, username, userPture, headPic } = this.$store.getters
      this.userinfo = {
        userId,
        username,
        avatar: userPture || headPic,
        room: this.roomId,
      }
      this.clientOnConnectHandle()
    },
    clientOnConnectHandle() {
      const socket = new SockJS(ROOM_URL) //连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
      const stompClient = Stomp.over(socket)
      stompClient.debug = false
      stompClient.connect(headers, (frame) => {
        stompClient.subscribe('/topic/chatRoom/' + this.roomId, (message) => {
          let bodyMsg = JSON.parse(message.body)
          // console.log(bodyMsg)
          bodyMsg.msg = this.tohtml(bodyMsg.msg)
          this.messageList.push(bodyMsg)
          this.scrollIntoBottom()
        })
      })
    },
    tohtml(str) {
      return str
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
    },
    sendMessage() {
      const myInput = document.getElementById('myInput')
      let msg = myInput.innerHTML.replace(/&nbsp;/g, '').trim()
      if (msg == '') return this.$message.warning('请输入内容')
      let { room, username, avatar, userId } = this.userinfo
      let obj = {
        from: username,
        roomId: room,
        username,
        avatar,
        msg,
        userId,
        sendTime: this.nowDate,
        extFiled: '', //扩展字段
      }
      const socket = new SockJS(ROOM_URL) //连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
      // 获取STOMP子协议的客户端对象
      const stompClient = Stomp.over(socket)
      stompClient.debug = false // 禁用控制台打印你连接时的内容
      stompClient.connect(headers, (frame) => {
        stompClient.send(
          '/app/chatRoom/' + this.roomId,
          {},
          JSON.stringify(obj),
        )
      })
      myInput.innerHTML = ''
    },
    scrollIntoBottom() {
      this.$nextTick(() => {
        let str = 'wrap' + (this.messageList.length - 1)
        let dom = this.$refs[str]
        if (dom && dom.length > 0) {
          dom[0].scrollIntoView(false)
        }
      })
    },
    handleSubmit() {
      this.sendMessage()
    },
    nowDate() {
      return moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    },
    keyDown(e) {
      if (e.keyCode == 17) {
        this.handleSubmit()
      }
    },
    handleShowEmoji() {
      this.$bus.$emit('showEmoji')
    },
    handleEmoji(item) {
      var img = document.createElement('img')
      img.setAttribute('src', item)
      const myInput = document.getElementById('myInput')
      myInput.appendChild(img)
    },
  },
}
</script>
<style scoped lang="scss">
.chat {
  .chat-title {
    font-size: 18px;
    color: #333;
    text-align: center;
    font-weight: normal;
  }
  .chat-wrap {
    width: 500px;
    height: calc(100vh - 230px);
    border-top: 1px solid #ccc;
    box-sizing: border-box;
    padding: 10px;
    overflow: auto;
    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 0;
    }
    &::-webkit-scrollbar {
      -webkit-appearance: none;
      width: 10px;
      height: 10px;
    }
    &::-webkit-scrollbar-thumb {
      cursor: pointer;
      border-radius: 5px;
      transition: color 0.2s ease;
      background-color: #ccc;
    }
    .message-box {
      overflow: hidden;
    }
  }
  .chat-form {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    box-sizing: border-box;
    padding: 10px 10px 10px 0px;
    border-top: 1px solid #ccc;
    .toolbar {
      height: 30px;
      width: 100%;
      ul {
        li {
          float: left;
          width: 30px;
          height: 30px;
          margin-left: 10px;
          cursor: pointer;
          background: url('../../../assets/wechat-sprit.png') no-repeat -404px -398px;
        }
      }
    }
    .chat-cont {
      padding-left: 10px;
      #myInput {
        width: 100%;
        height: 70px;
        font-size: 14px;
        color: #333;
        border: 0 none;
        outline: none;
        line-height: 1.5;
        overflow: auto;
      }
    }
    .emoji-wrap {
      position: absolute;
      left: 0;
      top: -277px;
      z-index: 10;
    }
    .chat-ipt {
      border: 0 none;
      background: transparent;
    }
    .btn-wrap {
      width: 100%;
      margin-top: 10px;
      text-align: right;
      .desc {
        color: #888;
        font-size: 12px;
        margin-left: 10px;
        margin-right: 7px;
      }
    }
  }
}
.chat-wrap {
  .system {
    overflow: hidden;
    width: 100%;
  }
  .message_system {
    text-align: center;
    margin: 10px auto;
    max-width: 50%;
  }

  .message_system .content {
    display: inline-block;
    font-size: 12px;
    padding: 1px 18px;
    color: #b2b2b2;
    border-radius: 2px;
  }

  .other {
    margin-bottom: 16px;
    float: left;
    width: 100%;
    padding-left: 20px;
    box-sizing: border-box;
  }

  .my {
    margin-bottom: 16px;
    float: right;
    width: 100%;
    text-align: right;
    padding-right: 20px;
    box-sizing: border-box;
  }

  .my.message .avatar {
    float: right;
  }

  .message .content {
    overflow: hidden;
  }
  .my.message .content .nickname {
    float: right;
    margin-right: 10px;
  }

  .message .content .nickname {
    font-weight: 400;
    padding-left: 10px;
    font-size: 12px;
    height: 26px;
    line-height: 20px;
    color: #999;
    width: 350px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-wrap: normal;
  }

  .message .avatar {
    float: left;
    cursor: pointer;
  }

  .my.message .bubble {
    background-color: #b2e281;
  }
  .message .bubble {
    max-width: 500px;
    min-height: 1em;
    display: inline-block;
    vertical-align: top;
    position: relative;
    text-align: left;
    font-size: 14px;
    border-radius: 3px;
    margin: 0 10px;
    background-color: #fff;
  }

  .message .bubble img {
    display: inline-block;
    cursor: pointer;
    max-width: 350px;
    max-height: 240px;
  }

  .other .bubble:before {
    position: absolute;
    top: 14px;
    left: -10px;
    border: 6px solid transparent;
    content: ' ';
    border-right-color: #fff;
    border-right-width: 4px;
  }

  .my .bubble:before {
    position: absolute;
    top: 14px;
    right: -10px;
    border: 6px solid transparent;
    content: ' ';
    border-left-color: #b2e281;
    border-left-width: 4px;
  }
  .bubble_cont {
    word-wrap: break-word;
    word-break: break-all;
    min-height: 24px;
    line-height: 24px;
    padding: 5px 6px;
  }
}
</style>
<style scoped>
.chat >>> .el-drawer__header {
  padding-bottom: 22px;
  margin: 0;
  background: #eee;
}
.chat >>> .el-drawer__body {
  position: relative;
  background: #eee;
}
.chat .chat-ipt >>> .el-textarea__inner {
  border: 0 none;
  background: transparent;
  color: #333;
  font-size: 16px;
}
#myInput >>> img,
.chat .chat-wrap ::v-deep img {
  background: #fff;
  margin-right: 1px;
}
#myInput >>> span,
#myInput >>> p,
.chat .chat-wrap .bubble_cont ::v-deep p,
.chat .chat-wrap .bubble_cont ::v-deep span {
  background: transparent !important;
  font-weight: normal !important;
  font-size: 14px !important;
  color: #333 !important;
}
.chat .chat-wrap .bubble_cont ::v-deep img {
  vertical-align: top;
}
</style>